<?php
/**
 * 地图 Api
 *
 * Created by PhpStorm.
 * User: zjx
 * Date: 2017/1/12
 * Time: 14:34
 */

namespace App\Services\BaiduGeoService;


use GuzzleHttp\Client as GuzzleClient;

class MapApi
{
    const RESPONSE_STATUS_OK = 0;

    protected $guzzle;
    protected $ak;

    public function __construct()
    {
        $this->guzzle = new GuzzleClient;
        $this->ak = config('pkx.baidu.api_ak');
    }

    /**
     * 逆地理编码 - 通过经纬反查地理位置信息
     *
     * @link http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding-abroad
     *
     * @test
     *
     * @param float $latitude
     * @param float $longitude
     *
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function geoCodeReverseQuery(float $latitude,
                                        float $longitude): array
    {
        $params = [
            'location' => $latitude . ',' . $longitude,
            'ak'       => $this->ak,
            'output'   => 'json',
        ];

        $url = sprintf(GeoApiList::GEO_CODER, http_build_query($params));
        /**
         * @var string $res
         *
         * @see GeoApiRespMock::geoCodeReverseQuery()
         */
        $res = $this->guzzle->request('GET', $url)->getBody();

        return json_decode($res, true);
    }

    /**
     * @param $latitude
     * @param $longitude
     *
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getLocationCode($latitude, $longitude)
    {
        $location_code = [
            'province' => null ,
            'city' =>  null
        ];

        $res = $this->geoCodeReverseQuery($latitude, $longitude);
        if (((int) $res['status']) !== 0) {
            logger($res['message']);
            return $location_code;
        } 

        $address = $res['result']['addressComponent'];
        $province_map = GBT22602007::provinceCodeMap();
        $city_map = GBT22602007::cityCodeMap();
        
        if (isset($province_map[$address['province']])) {
            $location_code['province'] = $province_map[$address['province']];
        }
        
        if (isset($city_map[$address['city']])) {
            $location_code['city'] =  $city_map[$address['city']];
        }
        
        return $location_code;
    }

    /**
     * @param string $address
     *
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getLocationQuery(string $address)
    {
        $params = [
            'address' => $address,
            'ak'      => $this->ak,
            'output'  => 'json',
        ];

        $url = sprintf(GeoApiList::GEO_CODER, http_build_query($params));

        /**
         * @var string $res
         *
         * @see GeoApiRespMock::getLocationQuery()
         * @see GeoApiRespMock::getLocationQueryError()
         */
        $res = $this->guzzle->request('GET', $url)->getBody();

        return json_decode($res, true);
    }

}

